-- tree_house_level_match
-- Created by dengc Mar/11/2016
-- 成就：树屋道具等级达标

-- 内部函数声明
local whenMatch;

-- 关注树屋事件
EventMgr.register("achievements/tree_house_level_match", event.TREE_HOUSE_LEVEL_MATCH, function(args)
    whenMatch(args);
end);

-- 事件的回调
whenMatch = function(args)
    local treeHouse = args["treeHouse"];
    local skillId = args["skillId"];

    -- 玩家不在地牢中
    if not DungeonM.isInDungeon() then
        return;
    end

    -- 获取当前所在的地牢区域
    local area = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("tree_house_level_match");

    -- 判断树屋道具等级是否达到XX
    local function isLevelMatch(needArgs)
        if type(skillId) ~= "number" then
            return false;
        end

        local treeHouseData = treeHouse:getSaveData();
        local skillLvel = treeHouseData["skills"][skillId];
        if skillLvel >= needArgs then
            return true;
        end
        return false;
    end

    -- 尝试完成等级成就
    for _, id in pairs(ids) do
        -- 已经完成了
        if true == AchievementM.isCompleted(id) then
            return false;
        end

        -- 不是该迷宫的成就
        if not AchievementM.isBelongTo(id, area) then
            return false;
        end

        -- 获取成就参数
        local ruleArgs = AchievementM.query(id, "rule_arg");
        local needArgs = ruleArgs["args"];

        -- 尝试完成道具等级指标成就
        if isLevelMatch(needArgs) then
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = AchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local value   = ruleArg["args"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{0}", value);

        return desc;
    end,
};
